package com.bank.frame;

import com.bank.dao.AccountDAO;
import com.bank.dao.RecordDAO;
import com.bank.utils.SystemConstants;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;

/**
 * 添加和修改数据的表单页
 */
public class TransferPanel extends JInternalFrame {

    public TransferPanel(Object selectedId) {
        super("转账", true, true, true, true);
        this.setSize(SystemConstants.FRAME_WIDTH - 20, SystemConstants.FRAME_HEIGHT - 50);
        // 创建内容面板
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        // 设置内部窗口的内容面板
        this.setContentPane(panel);
        Box boxBase = Box.createHorizontalBox();
        Box boxLeft = Box.createVerticalBox();
        // 左边的部分，是标签
        boxLeft.add(new JLabel("收款人"));
        boxLeft.add(Box.createVerticalStrut(8));
        boxLeft.add(new JLabel("收款账号"));
        boxLeft.add(Box.createVerticalStrut(8));
        boxLeft.add(new JLabel("付款卡"));
        boxLeft.add(Box.createVerticalStrut(8));
        boxLeft.add(new JLabel("可用余额"));
        boxLeft.add(Box.createVerticalStrut(8));
        boxLeft.add(new JLabel("转账金额"));
        boxLeft.add(Box.createVerticalStrut(8));
        boxLeft.add(new JLabel("转账附言"));
        boxLeft.add(Box.createVerticalStrut(30));
        // 右边的部分，是文本框，和上面boxLeft的内容顺序对应
        Box boxRight = Box.createVerticalBox();
        JTextField field1 = new JTextField(10);// 收款人
        boxRight.add(field1);
        boxRight.add(Box.createVerticalStrut(5));
        JTextField field2 = new JTextField(10);// 收款账号
        boxRight.add(field2);
        boxRight.add(Box.createVerticalStrut(5));

        // 获取当前登录者的所有卡，在转账时可以自由选择要转账的卡
        Object[][] accounts = AccountDAO.search(1, MainFrame.user.getUsername());
        JComboBox<String> combo = new JComboBox<>();
        boxRight.add(combo);
        JLabel balanceLabel = new JLabel("-");
        boxRight.add(balanceLabel);
        for (Object[] a : accounts) {
            // 注销的卡不能参与转账，只有有效状态的能被显示出来
            if (SystemConstants.ACCOUNT_STATUS_AVALIABLE.equals(a[7].toString())) {
                combo.addItem(a[0].toString());
            }
        }
        // 监听下拉框的事件，变更选项之后会重新加载余额
        combo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                String item = (String) combo.getSelectedItem();
                Object[] account = AccountDAO.findByCard(item);
                balanceLabel.setText("￥" + account[4]);
            }
        });
        // 如果在列表页选中了一张卡进来之后要默认选中这张卡并显示余额
        if (selectedId != null) {
            combo.setSelectedItem(selectedId);
            Object[] account = AccountDAO.findByCard(selectedId.toString());
            balanceLabel.setText("￥" + account[4]);
        } else {
            // 没有选中默认卡，就选中第一张卡
            combo.setSelectedItem(0);
            Object[] account = AccountDAO.findByCard(accounts[0][0].toString());
            balanceLabel.setText("￥" + account[4]);
        }
        JTextField field3 = new JTextField(10);// 转账金额
        boxRight.add(field3);
        boxRight.add(Box.createVerticalStrut(5));
        JTextField field4 = new JTextField(10);// 附言
        boxRight.add(field4);
        boxRight.add(Box.createVerticalStrut(5));

        JButton btn = new JButton("提交");
        btn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                double amount;
                try {// 必须输入有效的浮点数或整数
                    amount = Double.parseDouble(field3.getText());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(btn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if (amount <= 0) {
                    JOptionPane.showMessageDialog(btn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if (combo.getSelectedItem().toString().equals(field2.getText())) {
                    //  判断转入和转出是不是同一张卡
                    JOptionPane.showMessageDialog(btn.getParent(), "转入转出不能是同一张卡", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 转出账户
                Object[] accountOut = AccountDAO.findByCard(combo.getSelectedItem().toString());
                if (amount > (double) accountOut[4]) {
                    JOptionPane.showMessageDialog(btn.getParent(), "余额不足", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(accountOut[7].toString())) {
                    JOptionPane.showMessageDialog(btn.getParent(), "付款账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 收款账户，转入的
                Object[] accountIn = AccountDAO.findByCard(field2.getText());
                // 收款人账号不存在，或者收款人姓名不对或者已经 注销
                if (accountIn == null || !accountIn[2].equals(field1.getText())
                        || SystemConstants.ACCOUNT_STATUS_DISABLE.equals(accountIn[7].toString())) {
                    JOptionPane.showMessageDialog(btn.getParent(), "收款人账号无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                String input = JOptionPane.showInputDialog(btn.getParent(),
                        "您正在向" + field1.getText() + "转账" + amount + "元，确认转账请输入取款密码", "系统提示",
                        JOptionPane.WARNING_MESSAGE);
                if (input == null) {
                    return;
                }
                if (!input.equals(accountOut[8])) {
                    JOptionPane.showMessageDialog(btn.getParent(), "密码错误", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 如果付款账户是二类卡，二类卡单日累计不能转出(含取款)超出1万
                if (SystemConstants.ACCOUNT_TYPE_II.equals(accountOut[6])) {
                    double today = RecordDAO.getTodayAmount(accountOut[0].toString(), "out");
                    // amount是正数
                    if (today - amount < -10000) {
                        JOptionPane.showMessageDialog(btn.getParent(), "Ⅱ类卡单日转出(含取款、转账)限额1万，已交易" + today, "系统提示",
                                JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                }
                // 如果收款账户是二类卡，二类卡单日累计不能转入(含存款)超出1万
                if (SystemConstants.ACCOUNT_TYPE_II.equals(accountIn[6])) {
                    double today = RecordDAO.getTodayAmount(accountIn[0].toString(), "in");
                    if (today + amount > 10000) {
                        JOptionPane.showMessageDialog(btn.getParent(), "对方Ⅱ类卡单日转入(含存款)限额1万", "系统提示",
                                JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                }
                // 减掉付款人余额
                accountOut[4] = (double) accountOut[4] - amount;
                AccountDAO.update(accountOut[0].toString(), accountOut);
                // 增加收款人余额
                accountIn[4] = (double) accountIn[4] + amount;
                AccountDAO.update(accountIn[0].toString(), accountIn);
                // 构建转出记录： "交易编号", "卡号", "交易时间", "交易类型", "交易金额", "余额", "对方姓名",
                // "对方账户", "交易备注"
                Object[] recordOut = new Object[]{System.currentTimeMillis(), accountOut[0],
                        SystemConstants.DATE_FORMAT.format(new Date()), SystemConstants.TRADE_TYPE_OUT, "-" + amount,
                        accountOut[4], accountIn[2], accountIn[0], field4.getText()};
                RecordDAO.add(recordOut);

                // 转入记录，收款方的交易记录
                Object[] recordIn = new Object[]{recordOut[0], accountIn[0], recordOut[2],
                        SystemConstants.TRADE_TYPE_IN, "+" + amount, accountIn[4], accountOut[2], accountOut[0],
                        field4.getText()};
                RecordDAO.add(recordIn);
                // 回到列表页
                com.bank.frame.UserPanel.setContent(new RecordTablePanel(accountOut[0].toString(), accountOut[1].toString()));
            }
        });
        boxRight.add(btn);
        boxBase.add(boxLeft);
        boxBase.add(Box.createHorizontalStrut(8));
        boxBase.add(boxRight);
        panel.add(boxBase);
        // 显示内部窗口
        this.setVisible(true);
    }
}
